<?php
ob_start();
include("dbinfo.inc.php");
mysql_connect(localhost,$username,$password);
@mysql_select_db($database) or die( "Unable to select database"); 

$query="select ID from TrailHead where name like '$_POST[TrailHeadName]';";
$resultID=mysql_query($query);
if (!$resultID) {
  echo "Error selecting ID from TrailHead: " . mysql_error();
  die("");
}
$headID=mysql_result($resultID,0, "ID");

// deletes all saved trails associated w/ the trail head
$query="DELETE FROM Saved where headID=$headID;";
if (!mysql_query($query)) {
  echo "Error deleting saved trails: " . mysql_error();
}

// deletes all trails associated w/ the head
$query=" SELECT ID FROM Trail where headID=$headID; ";
$resultTrails=mysql_query($query);
if (!$resultTrails) {
  echo "Error selecting ID from Trail: " . mysql_error();
}
$numTrails=mysql_numrows($resultTrails);

// deletes all reviews associated w/ all trails being removed
for ($i=0; $i<$numTrails; $i++) {
  $trailID=mysql_result($resultTrails,$i,"ID");
  $query="DELETE FROM Review where trailID=$trailID;";
  if (!mysql_query($query)) {
    echo "Error deleting reviews: " . mysql_error();
  }
}

// deletes all trails associated w/ the trail head
$query=" DELETE FROM Trail where headID=$headID; ";
if (!mysql_query($query)) {
  echo "Error deleting trails: " . mysql_error();
}

// deletes the trail head
$query=" DELETE FROM TrailHead where ID=$headID; ";
if (!mysql_query($query)) {
  echo "Error deleting trail head: " . mysql_error();
}

mysql_close();
header("Location: index.php");
ob_flush();
?> 
